/**
 * 用户订单接口
 */
const express = require('express')
const order = express.Router()

// 引入数据库
const db = require('../utils/db')
// 引入uuid生成订单
const { v4: uuidv4 } = require('uuid')

/* 获取用户订单 */
order.get('/getorders', (req, res) => {
   const { username } = req.query
   const sql = `SELECT * FROM address WHERE username='${username}'`
   db.query(sql, async (err, results) => {
      const orderList = []
      if (results.length >= 1) {
         for(let address of results) {
            // 获取到地址id对应的收货人姓名
            let orders = await getOrder(address.id)
            if (orders && orders.length > 0) {
               orders.forEach(order => {
                  orderList.push({...order, realname: address.realname})
               })
            }
         }
         res.json({ orderList, msg: 'ok', code: 1})
      }
      else res.json({ orderList, msg: 'failed', code: 0})
   })
})
// 根据该账号收货地址id获取对应用户的订单
function getOrder(address_id) {
   return new Promise((resolve) => {
      const sql = `SELECT * FROM orders WHERE address_id=${address_id}`
      db.query(sql, (err, results) => {
         resolve(results)
      })
   })
}

/* 根据订单id获取对应订单详情 */
order.post('/getorderdetailbyid', (req, res) => {
   const { orderId } = req.body
   const sql = `
      SELECT * FROM orders WHERE id=${orderId};
      SELECT * FROM orders_goods WHERE orders_id=${orderId};
   `
   db.query(sql, (err, results) => {
      if (results.length >= 2) {
         let orderInfo = {
            ...results[0][0],
            goods: results[1]
         }
         res.json({ code: 1, orderInfo, msg: 'ok' })
      } else {
         res.json({ code: 0, orderInfo: {}, msg: 'none' })
      }
   })
})


/**
 * 新增一条订单
 * @param {Number} address_id 收货地址id
 * @param {String} food_totalprice 该订单中商品总价
 * @param {string} username 用户的账号名
 * @param {string} shopname 订单对应店铺名称
 * @param {Array} goods 订单中所有的商品
 */
order.post('/insertorder', (req, res) => {
   const { address_id, food_totalprice, username, goods, shopname, shoplist_id} = req.body
   const order_num = uuidv4()
   const sql = `INSERT INTO orders(order_num,address_id,food_totalprice,username,state,shopname,shoplist_id) VALUES('${order_num}',${address_id},'${food_totalprice}','${username}',0,'${shopname}',${shoplist_id})`
   db.query(sql, async (err, results) => {
      if(results.affectedRows >= 1) {
         // 获取新添加的那个订单ID
         const { orders_id } = await getOrderIdByOrderNum(order_num)
         // 添加商品到订单商品列表中
         for (let v of goods) {
            v.foodpic = v.foodpic.slice(v.foodpic.lastIndexOf('/') + 1)
            await addGoodsToOrder_goods(v.foodname, v.foodpic, v.count, orders_id, v.price)
         }
         res.json({ orderNum: order_num, msg: 'ok', code: 1});
      } else {
         res.json({orderNum: '', msg: 'failed', code: 0})
      }
   })
})
//获取订单号对应的订单ID
function getOrderIdByOrderNum(order_num) {
   return new Promise((resolve, reject) => {
      const sql = `SELECT id FROM orders WHERE order_num='${order_num}'`
      db.query(sql, (err, results) => {
         resolve({ orders_id: results[0].id })
      })
   })
}
// 添加商品到订单列表中
function addGoodsToOrder_goods(foodname,pic,count,orders_id,price) {
   return new Promise((resolve, reject) => {
      const sql = `INSERT INTO orders_goods(foodname,pic,count,orders_id,price) VALUES('${foodname}','${pic}',${Number(count)},${Number(orders_id)},'${price}')`
      db.query(sql,(err, results)=>{
         resolve('ok')
      })
   })
}

/* 删除一条订单 */
order.post('/delorder', (req, res) => {
   const { orderId } = req.body
   const sql = `DELETE FROM orders WHERE id=${orderId}`

   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) {
         delOrderGoods(orderId) // 删除订单对应的所有商品
         res.json({ msg: 'ok', code: 1 })
      }
      else res.json({ msg: 'failed', code: 0 })
   })
})
function delOrderGoods(orderId) {
   const sql = `DELETE FROM orders_goods WHERE orders_id=${orderId}`
   db.query(sql, ()=>{})
}

/* 完成一条订单 */
order.post('/finishorder', (req, res) => {
   const { orderId } = req.body
   const sql = `UPDATE orders SET state=1 WHERE id=${orderId}`
   db.query(sql, (err, results) => {
      if (results.affectedRows >= 1) res.json({ msg: 'ok', code: 1 })
      else res.json({ msg: 'failed', code: 0 })
   })
})

/* 评论一条订单 */
order.get('/commentorder', (req, res) => {
   const { orderId } = req.query
   const sql = `UPDATE orders SET iscomment=1 WHERE id=${orderId}`
   db.query(sql,()=>{})
})

module.exports = order